{% extends "base.html" %}

{% block title %}日程助手 - 生活助手{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1><i class="bi bi-calendar-event"></i> 日程助手</h1>
            <p class="text-muted">管理您的日程和事件</p>
        </div>
        <button class="btn btn-primary btn-custom" data-bs-toggle="modal" data-bs-target="#addEventModal">
            <i class="bi bi-plus-circle"></i> 添加事件
        </button>
    </div>
</div>

<!-- 日历导航 -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row align-items-center">
            <div class="col-md-4">
                <div class="btn-group">
                    <button class="btn btn-outline-secondary" onclick="previousMonth()">
                        <i class="bi bi-chevron-left"></i>
                    </button>
                    <button class="btn btn-outline-secondary" onclick="goToToday()">今天</button>
                    <button class="btn btn-outline-secondary" onclick="nextMonth()">
                        <i class="bi bi-chevron-right"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-4 text-center">
                <h4 id="calendar-title" class="mb-0">2025年1月</h4>
            </div>
            <div class="col-md-4">
                <select class="form-select" id="filter-category" onchange="loadMonthEvents()">
                    <option value="">所有分类</option>
                    <option value="会议">会议</option>
                    <option value="约会">约会</option>
                    <option value="学习">学习</option>
                    <option value="运动">运动</option>
                    <option value="其他">其他</option>
                </select>
            </div>
        </div>
    </div>
</div>

<!-- 日历视图 -->
<div class="card mb-4">
    <div class="card-body">
        <!-- 星期标题 -->
        <div class="row text-center mb-2 fw-bold">
            <div class="col">周日</div>
            <div class="col">周一</div>
            <div class="col">周二</div>
            <div class="col">周三</div>
            <div class="col">周四</div>
            <div class="col">周五</div>
            <div class="col">周六</div>
        </div>
        <!-- 日期网格 -->
        <div id="calendar-grid"></div>
    </div>
</div>

<!-- 添加事件模态框 -->
<div class="modal fade" id="addEventModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加事件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="add-event-form">
                    <div class="mb-3">
                        <label class="form-label">事件标题 *</label>
                        <input type="text" class="form-control" id="event-title" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="event-description" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">开始时间 *</label>
                        <input type="datetime-local" class="form-control" id="event-start-time" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">结束时间</label>
                        <input type="datetime-local" class="form-control" id="event-end-time">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">地点</label>
                        <input type="text" class="form-control" id="event-location">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">分类</label>
                        <select class="form-select" id="event-category">
                            <option value="会议">会议</option>
                            <option value="约会">约会</option>
                            <option value="学习">学习</option>
                            <option value="运动">运动</option>
                            <option value="其他" selected>其他</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">提醒时间</label>
                        <select class="form-select" id="event-reminder">
                            <option value="1">提前1分钟</option>
                            <option value="15" selected>提前15分钟</option>
                            <option value="30">提前30分钟</option>
                            <option value="60">提前1小时</option>
                            <option value="1440">提前1天</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">颜色（重要程度）</label>
                        <div class="d-flex gap-3 flex-wrap" id="color-selector-container">
                            <div class="text-center">
                                <button type="button" class="btn color-selector" style="background-color: #dc3545; width: 50px; height: 50px;" onclick="selectColor('#dc3545')"></button>
                                <small class="d-block mt-1 text-muted">最重要</small>
                            </div>
                            <div class="text-center">
                                <button type="button" class="btn color-selector" style="background-color: #fd7e14; width: 50px; height: 50px;" onclick="selectColor('#fd7e14')"></button>
                                <small class="d-block mt-1 text-muted">重要</small>
                            </div>
                            <div class="text-center">
                                <button type="button" class="btn color-selector selected" style="background-color: #4a90e2; width: 50px; height: 50px;" onclick="selectColor('#4a90e2')"></button>
                                <small class="d-block mt-1 text-muted">一般</small>
                            </div>
                            <div class="text-center">
                                <button type="button" class="btn color-selector" style="background-color: #28a745; width: 50px; height: 50px;" onclick="selectColor('#28a745')"></button>
                                <small class="d-block mt-1 text-muted">次要</small>
                            </div>
                            <div class="text-center">
                                <button type="button" class="btn color-selector" style="background-color: #6f42c1; width: 50px; height: 50px;" onclick="selectColor('#6f42c1')"></button>
                                <small class="d-block mt-1 text-muted">最不重要</small>
                            </div>
                        </div>
                        <input type="hidden" id="event-color" value="#4a90e2">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addEvent()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 某日事件列表模态框 -->
<div class="modal fade" id="dayEventsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-calendar-day"></i> <span id="day-events-date"></span> 的事件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="day-events-list">
                    <!-- 事件列表将在这里动态生成 -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 查看事件模态框 -->
<div class="modal fade" id="viewEventModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="view-event-title"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="view-event-id">
                <div class="mb-3">
                    <label class="text-muted">时间</label>
                    <p id="view-event-time"></p>
                </div>
                <div class="mb-3" id="view-location-container" style="display:none;">
                    <label class="text-muted">地点</label>
                    <p id="view-event-location"></p>
                </div>
                <div class="mb-3" id="view-description-container" style="display:none;">
                    <label class="text-muted">描述</label>
                    <p id="view-event-description"></p>
                </div>
                <div class="mb-3">
                    <label class="text-muted">分类</label>
                    <p><span class="badge bg-secondary" id="view-event-category"></span></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="deleteEventFromView()">删除</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentYear = new Date().getFullYear();
let currentMonth = new Date().getMonth() + 1;
let selectedColor = '#4a90e2';
let eventsData = {};

// 格式化日期时间为本地时间（datetime-local格式）
function formatDateTimeLocal(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 选择颜色
function selectColor(color) {
    selectedColor = color;
    document.getElementById('event-color').value = color;
    
    // 移除所有选中状态
    document.querySelectorAll('#color-selector-container .color-selector').forEach(btn => {
        btn.classList.remove('selected');
    });
    
    // 添加当前选中状态
    event.target.classList.add('selected');
}

// 上个月
function previousMonth() {
    currentMonth--;
    if (currentMonth < 1) {
        currentMonth = 12;
        currentYear--;
    }
    loadMonthEvents();
}

// 下个月
function nextMonth() {
    currentMonth++;
    if (currentMonth > 12) {
        currentMonth = 1;
        currentYear++;
    }
    loadMonthEvents();
}

// 回到当前月
function goToToday() {
    const today = new Date();
    currentYear = today.getFullYear();
    currentMonth = today.getMonth() + 1;
    loadMonthEvents();
}

// 加载月份事件
function loadMonthEvents() {
    document.getElementById('calendar-title').textContent = `${currentYear}年${currentMonth}月`;
    
    fetch(`/schedule/api/month-events?year=${currentYear}&month=${currentMonth}`)
        .then(response => response.json())
        .then(data => {
            eventsData = data.events_by_date;
            renderCalendar();
        });
}

// 渲染日历
function renderCalendar() {
    // 计算月份第一天是星期几
    const firstDay = new Date(currentYear, currentMonth - 1, 1).getDay();
    // 计算月份天数
    const daysInMonth = new Date(currentYear, currentMonth, 0).getDate();
    
    const grid = document.getElementById('calendar-grid');
    let html = '<div class="row g-2">';
    
    // 填充空白日期
    for (let i = 0; i < firstDay; i++) {
        html += '<div class="col"></div>';
    }
    
    // 填充日期
    const today = new Date();
    const isCurrentMonth = today.getFullYear() === currentYear && today.getMonth() + 1 === currentMonth;
    
    for (let day = 1; day <= daysInMonth; day++) {
        const dateKey = `${currentYear}-${String(currentMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        const events = eventsData[dateKey] || [];
        const isToday = isCurrentMonth && today.getDate() === day;
        
        html += `
            <div class="col">
                <div class="calendar-day ${isToday ? 'bg-primary bg-opacity-10' : ''}" onclick="showDayEvents('${dateKey}')">
                    <div class="fw-bold mb-1">${day}</div>
                    ${events.slice(0, 2).map(e => `
                        <div class="calendar-event" style="background-color: ${e.color}">
                            ${e.title}
                        </div>
                    `).join('')}
                    ${events.length > 2 ? `<small class="text-muted">+${events.length - 2}更多</small>` : ''}
                </div>
            </div>
        `;
        
        // 每7天换行
        if ((firstDay + day) % 7 === 0) {
            html += '</div><div class="row g-2">';
        }
    }
    
    html += '</div>';
    grid.innerHTML = html;
}

// 显示某日的事件
function showDayEvents(dateKey) {
    const events = eventsData[dateKey] || [];
    
    if (events.length === 0) {
        // 如果没有事件，打开添加事件对话框并预填日期
        const modal = new bootstrap.Modal(document.getElementById('addEventModal'));
        document.getElementById('event-start-time').value = dateKey + 'T09:00';
        modal.show();
        return;
    }
    
    // 显示该日所有事件列表
    const date = new Date(dateKey);
    document.getElementById('day-events-date').textContent = date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' });
    
    const container = document.getElementById('day-events-list');
    container.innerHTML = events.map(event => {
        const startTime = new Date(event.start_time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        const endTime = event.end_time ? ' - ' + new Date(event.end_time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : '';
        
        return `
            <div class="card mb-2" style="border-left: 4px solid ${event.color}">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <h6 class="mb-1">${event.title}</h6>
                            <small class="text-muted">
                                <i class="bi bi-clock"></i> ${startTime}${endTime}
                                ${event.location ? `<br><i class="bi bi-geo-alt"></i> ${event.location}` : ''}
                            </small>
                        </div>
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary" onclick="editEvent(${event.id})">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-outline-danger" onclick="deleteEvent(${event.id})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                    ${event.description ? `<p class="mb-0 mt-2 text-muted small">${event.description}</p>` : ''}
                </div>
            </div>
        `;
    }).join('');
    
    new bootstrap.Modal(document.getElementById('dayEventsModal')).show();
}

// 添加事件
function addEvent() {
    const data = {
        title: document.getElementById('event-title').value,
        description: document.getElementById('event-description').value,
        start_time: document.getElementById('event-start-time').value,
        end_time: document.getElementById('event-end-time').value,
        location: document.getElementById('event-location').value,
        category: document.getElementById('event-category').value,
        reminder_minutes: parseInt(document.getElementById('event-reminder').value),
        color: document.getElementById('event-color').value
    };
    
    if (!data.title || !data.start_time) {
        showAlert('请填写必填字段', 'warning');
        return;
    }
    
    fetch('/schedule/api/events', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(err => {
                throw new Error(err.error || '添加失败');
            });
        }
        return response.json();
    })
    .then(result => {
        if (result.success) {
            showAlert('添加成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('addEventModal')).hide();
            document.getElementById('add-event-form').reset();
            selectedColor = '#4a90e2';
            
            // 重置颜色选择状态
            document.querySelectorAll('#color-selector-container .color-selector').forEach(btn => {
                btn.classList.remove('selected');
                if (btn.style.backgroundColor.includes('74, 144, 226') || btn.style.backgroundColor === 'rgb(74, 144, 226)') {
                    btn.classList.add('selected');
                }
            });
            
            loadMonthEvents();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('添加失败: ' + error.message, 'danger');
    });
}

// 编辑事件
function editEvent(eventId) {
    // 先关闭事件列表模态框
    const dayEventsModal = bootstrap.Modal.getInstance(document.getElementById('dayEventsModal'));
    if (dayEventsModal) {
        dayEventsModal.hide();
    }
    
    fetch(`/schedule/api/events/${eventId}`)
        .then(response => response.json())
        .then(event => {
            // 填充表单
            document.getElementById('event-title').value = event.title;
            document.getElementById('event-description').value = event.description || '';
            
            // 格式化开始时间为本地时间
            const startTime = new Date(event.start_time);
            document.getElementById('event-start-time').value = formatDateTimeLocal(startTime);
            
            // 格式化结束时间为本地时间
            if (event.end_time) {
                const endTime = new Date(event.end_time);
                document.getElementById('event-end-time').value = formatDateTimeLocal(endTime);
            } else {
                document.getElementById('event-end-time').value = '';
            }
            
            document.getElementById('event-location').value = event.location || '';
            document.getElementById('event-category').value = event.category;
            document.getElementById('event-reminder').value = event.reminder_minutes;
            document.getElementById('event-color').value = event.color;
            selectedColor = event.color;
            
            // 移除所有颜色选中状态并高亮当前颜色
            document.querySelectorAll('#color-selector-container .color-selector').forEach(btn => {
                btn.classList.remove('selected');
                // 比较背景颜色
                const btnColor = btn.style.backgroundColor;
                const eventColor = event.color.toLowerCase();
                // 将rgb颜色转换为hex进行比较
                if (btnColor.includes('rgb')) {
                    const rgb = btnColor.match(/\d+/g);
                    const hex = '#' + ((1 << 24) + (parseInt(rgb[0]) << 16) + (parseInt(rgb[1]) << 8) + parseInt(rgb[2])).toString(16).slice(1);
                    if (hex.toLowerCase() === eventColor) {
                        btn.classList.add('selected');
                    }
                } else if (btnColor.toLowerCase() === eventColor) {
                    btn.classList.add('selected');
                }
            });
            
            // 稍微延迟打开编辑模态框，确保列表框完全关闭
            setTimeout(() => {
                // 修改按钮为更新
                const modal = new bootstrap.Modal(document.getElementById('addEventModal'));
                document.querySelector('#addEventModal .modal-title').textContent = '编辑事件';
                document.querySelector('#addEventModal .btn-primary').textContent = '更新';
                document.querySelector('#addEventModal .btn-primary').setAttribute('onclick', `updateEvent(${eventId})`);
                modal.show();
            }, 200);
        });
}

// 更新事件
function updateEvent(eventId) {
    const data = {
        title: document.getElementById('event-title').value,
        description: document.getElementById('event-description').value,
        start_time: document.getElementById('event-start-time').value,
        end_time: document.getElementById('event-end-time').value,
        location: document.getElementById('event-location').value,
        category: document.getElementById('event-category').value,
        reminder_minutes: parseInt(document.getElementById('event-reminder').value),
        color: document.getElementById('event-color').value
    };
    
    if (!data.title || !data.start_time) {
        showAlert('请填写必填字段', 'warning');
        return;
    }
    
    fetch(`/schedule/api/events/${eventId}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(err => {
                throw new Error(err.error || '更新失败');
            });
        }
        return response.json();
    })
    .then(result => {
        if (result.success) {
            showAlert('更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('addEventModal')).hide();
            resetAddEventForm();
            loadMonthEvents();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('更新失败: ' + error.message, 'danger');
    });
}

// 删除事件
function deleteEvent(eventId) {
    if (!confirm('确定要删除这个事件吗？')) return;
    
    fetch(`/schedule/api/events/${eventId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('dayEventsModal'))?.hide();
            loadMonthEvents();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('删除失败', 'danger');
    });
}

// 重置添加事件表单
function resetAddEventForm() {
    document.querySelector('#addEventModal .modal-title').textContent = '添加事件';
    document.querySelector('#addEventModal .btn-primary').textContent = '添加';
    document.querySelector('#addEventModal .btn-primary').setAttribute('onclick', 'addEvent()');
    document.getElementById('add-event-form').reset();
    selectedColor = '#4a90e2';
    
    // 重置颜色选择状态（默认选中蓝色"一般"）
    document.querySelectorAll('#color-selector-container .color-selector').forEach(btn => {
        btn.classList.remove('selected');
        if (btn.style.backgroundColor.includes('74, 144, 226') || btn.style.backgroundColor === 'rgb(74, 144, 226)') {
            btn.classList.add('selected');
        }
    });
}

// 查看事件
function viewEvent(eventId) {
    fetch(`/schedule/api/events/${eventId}`)
        .then(response => response.json())
        .then(event => {
            document.getElementById('view-event-id').value = event.id;
            document.getElementById('view-event-title').textContent = event.title;
            document.getElementById('view-event-category').textContent = event.category;
            
            // 格式化时间
            const startTime = new Date(event.start_time).toLocaleString('zh-CN');
            const endTime = event.end_time ? ' - ' + new Date(event.end_time).toLocaleString('zh-CN') : '';
            document.getElementById('view-event-time').textContent = startTime + endTime;
            
            // 地点
            if (event.location) {
                document.getElementById('view-event-location').textContent = event.location;
                document.getElementById('view-location-container').style.display = 'block';
            } else {
                document.getElementById('view-location-container').style.display = 'none';
            }
            
            // 描述
            if (event.description) {
                document.getElementById('view-event-description').textContent = event.description;
                document.getElementById('view-description-container').style.display = 'block';
            } else {
                document.getElementById('view-description-container').style.display = 'none';
            }
            
            new bootstrap.Modal(document.getElementById('viewEventModal')).show();
        });
}

// 从查看对话框删除事件
function deleteEventFromView() {
    const eventId = document.getElementById('view-event-id').value;
    if (!confirm('确定要删除这个事件吗？')) return;
    
    fetch(`/schedule/api/events/${eventId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('viewEventModal')).hide();
            loadMonthEvents();
        }
    });
}

// 页面加载
document.addEventListener('DOMContentLoaded', function() {
    loadMonthEvents();
});
</script>
{% endblock %}

